/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import me.zhengjie.modules.biz.domain.EnergyConsumption;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.EnergyConsumptionRepository;
import me.zhengjie.modules.biz.service.EnergyConsumptionService;
import me.zhengjie.modules.biz.service.dto.EnergyConsumptionDto;
import me.zhengjie.modules.biz.service.dto.EnergyConsumptionQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.EnergyConsumptionMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-09-05
**/
@Service
@RequiredArgsConstructor
public class EnergyConsumptionServiceImpl implements EnergyConsumptionService {

    private final EnergyConsumptionRepository energyConsumptionRepository;
    private final EnergyConsumptionMapper energyConsumptionMapper;

    @Override
    public Map<String,Object> queryAll(EnergyConsumptionQueryCriteria criteria, Pageable pageable){
        Page<EnergyConsumption> page = energyConsumptionRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(energyConsumptionMapper::toDto));
    }

    @Override
    public List<EnergyConsumptionDto> queryAll(EnergyConsumptionQueryCriteria criteria){
        return energyConsumptionMapper.toDto(energyConsumptionRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public EnergyConsumptionDto findById(Integer id) {
        EnergyConsumption energyConsumption = energyConsumptionRepository.findById(id).orElseGet(EnergyConsumption::new);
        ValidationUtil.isNull(energyConsumption.getId(),"EnergyConsumption","id",id);
        return energyConsumptionMapper.toDto(energyConsumption);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EnergyConsumptionDto create(EnergyConsumption resources) {
        return energyConsumptionMapper.toDto(energyConsumptionRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EnergyConsumption resources) {
        EnergyConsumption energyConsumption = energyConsumptionRepository.findById(resources.getId()).orElseGet(EnergyConsumption::new);
        ValidationUtil.isNull( energyConsumption.getId(),"EnergyConsumption","id",resources.getId());
        energyConsumption.copy(resources);
        energyConsumptionRepository.save(energyConsumption);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            energyConsumptionRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<EnergyConsumptionDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (EnergyConsumptionDto energyConsumption : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("类型 1新风 2.排风 3.空调", energyConsumption.getType());
            map.put("创建时间", energyConsumption.getCreatedAt());
            map.put("能耗值", energyConsumption.getValue());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public ArrayList<Map<String,Object>>data() throws ParseException {

//        HashMap <String,Object> data = new HashMap<>();
        ArrayList<Map<String,Object>> arrayList = new ArrayList<>();
        for (int i = 1; i <=3 ; i++) {
            HashMap<String,Object> dataMap = new HashMap<>();
            Long  time = System.currentTimeMillis();  //当前时间的时间戳
            long timestamp = time/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset();
            Calendar calendar = Calendar.getInstance();
            calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)-1,0,0,0);
            long timestamp1 = calendar.getTime().getTime();
            Float yesterdayData = energyConsumptionRepository.findBytime(i,timestamp1,timestamp);
            if (yesterdayData!=null){
                dataMap.put("yesterdayData",yesterdayData);
            }else {
                dataMap.put("yesterdayData",0);
            }

            calendar = Calendar.getInstance();
            calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)-1,1,0,0,0);
            timestamp = calendar.getTime().getTime();

            calendar = Calendar.getInstance();
            calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)-1,calendar.get(Calendar.DAY_OF_MONTH),23,59,59);
            calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            timestamp1 = calendar.getTime().getTime();
            Float lastMonthData = energyConsumptionRepository.findBytime(i,timestamp1,timestamp);
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            if (lastMonthData!=null){
                dataMap.put("lastMonthData",lastMonthData);
            }else {
                dataMap.put("lastMonthData",0);
            }

            if (yesterdayData==null||lastMonthData==null){
                dataMap.put("percent",0);
            }else {
                dataMap.put("percent",decimalFormat.format((lastMonthData-yesterdayData)/yesterdayData*100));
            }

            if (i==1){
                dataMap.put("title","新风");
            }else if (i==2){
                dataMap.put("title","排风");
            }else {
                dataMap.put("title","中央空调");
            }
            arrayList.add(dataMap);
        }
        return arrayList;
    }


    @Override
    public Map<String, Object> lastWeekData() {
        HashMap<String,Object> dataMap = new HashMap<>();

        Calendar calendar;
        for (int j = 1; j <=3 ; j++) {
            ArrayList<Float> arrayList = new ArrayList<>();
            for (int i = 1; i <= 14; i++) {
                calendar = Calendar.getInstance();
                calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)-15+i,0,0,0);
                long timestamp = calendar.getTime().getTime();
                calendar = Calendar.getInstance();
                calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)-15+i,23,59,59);
                long timestamp1 = calendar.getTime().getTime();
                Float data = energyConsumptionRepository.findBytime(j,timestamp,timestamp1);
                if (data!=null){
                    arrayList.add(data);
                }else {
                    arrayList.add((float) 0);
                }
            }
            if (j==1){
                dataMap.put("freshAirVentilator",arrayList);
            }else if (j==2){
                dataMap.put("exhaustFan",arrayList);
            }else {
                dataMap.put("airConditioner",arrayList);
            }
        }
        return dataMap;
    }


}
